<template>
  <el-radio-group
    v-model="vValue"
    v-bind="attrs"
    :disabled="disabled"
    @change="itemEvent('change', $event)"
  >
    <el-radio
      v-for="(item, index) in selectList"
      v-bind="item"
      :label="item.value"
      :key="index"
      :disabled="item.disabled"
    >
      <slot> {{ item.label }} </slot>
    </el-radio>
  </el-radio-group>
</template>

<script setup>
import _ from 'lodash';
import { vModelValue } from '@/utils/hooks.js';

const attrs = useAttrs();
const props = defineProps({
  modelValue: {
    type: [String, Number],
  },
  options: {
    // 下拉值集合
    type: Array,
    default: () => [],
  },
  filterKey: {
    // 下拉值label和value的取值字段名
    type: Object,
    default: () => ({
      label: 'label',
      value: 'value',
    }),
  },
});
const emits = defineEmits(['update:modelValue', 'itemEvent']);
const { newValue: key } = vModelValue(props, emits);
let vValue = ref(key);

// 值集过滤
const selectList = computed(() => {
  let list = [...props.options];
  if (list?.length) {
    const { label, value } = props.filterKey;
    list = list.map(item => ({
      label: item[label],
      value: item[value],
      disabled: item.disabled || false,
    }));
  }
  return list;
});

// 是否禁用
const disabled = computed(() => {
  return attrs.disabledFn && _.isFunction(attrs.disabledFn)
    ? attrs.disabledFn(attrs)
    : attrs.disabled || false;
});

// 事件
function itemEvent(eventName, $event) {
  emits('itemEvent', { eventName, value: $event || vValue.value, prop: attrs.prop });
}
</script>
